package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClazzService clazzService;
    @Override
    public PageResult<Student> pageList(StudentQueryParam student) {
        //创建page对象进行分页
        Page<Student> pageInfo = new Page<>(student.getPage(), student.getPageSize());
        //按时间倒序排序
        pageInfo.addOrder(OrderItem.desc("update_time"));
        //条件查询按照姓名、班级、学历进行查询
        lambdaQuery().like(student.getName() != null,Student::getName, student.getName()).eq(student.getDegree() != null,Student::getDegree, student.getDegree()).eq(student.getClazzId() != null,Student::getClazzId, student.getClazzId()).page( pageInfo);
        //获取分页数据集合
        List<Student> list = pageInfo.getRecords();
        if(!CollectionUtils.isEmpty( list)){
            //将所有的分页的数据集合的部门ID获取出来放到新的集合里面
            List<Integer> collect = list.stream().map(Student::getClazzId).collect(Collectors.toList());
            List<Clazz> clazzList = clazzService.listByIds(collect);
            if (!CollectionUtils.isEmpty( clazzList)){
                clazzList.forEach(clazz -> {
                    list.forEach(s -> {
                        if (s.getClazzId().equals(clazz.getId())){
                            s.setClazzName(clazz.getName());
                        }
                    });
                });

            }
        }
        long pages = pageInfo.getTotal();
        return new PageResult<>(pages, list);
    }

    @Override
    public void updateStudent(Student student) {
        //回显 数据
        Student oldStudent = getById( student.getId());

        //修改
        updateById(student);
        ;

    }

    @Override
    public void violation(Integer id, Integer score) {
        
    }
}
